package com.yy.finvideoplayer.videoview

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import android.media.AudioManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.SeekBar
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import com.bumptech.glide.Glide
import com.yy.finvideoplayer.HandleTouchEvent
import com.yy.finvideoplayer.IVideoPlayer
import com.yy.finvideoplayer.IVideoPlayer.Companion.MODE_WINDOW_FULLSCREEN
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_AUTO_COMPLETE
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_ERROR
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_NORMAL
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_PAUSE
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_PLAYING
import com.yy.finvideoplayer.IVideoPlayer.Companion.STATE_PREPARING
import com.yy.finvideoplayer.PlayListener
import com.yy.finvideoplayer.R
import com.yy.finvideoplayer.Util
import com.yy.finvideoplayer.databinding.FinVideoControlUiBinding
import com.yy.finvideoplayer.model.PlayerOptions
import com.yy.finvideoplayer.model.PlayerOptions.PlayBtnPosition
import com.yy.finvideoplayer.model.QSVideo
import com.yy.finvideoplayer.utils.BitmapSaveUtils
import com.yy.finvideoplayer.utils.PermissionUtils
import java.io.File
import java.io.FileOutputStream
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min

/**
 * @Description: VideoControlView
 * @Author: yiw89
 * @CreateDate: 2025/9/6 20:43
 * @Version: 1.0
 */
class VideoControlView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    private var playerOptions: PlayerOptions
) :FrameLayout(context, attrs, defStyleAttr),
    HandleTouchEvent.GestureEvent,
    SeekBar.OnSeekBarChangeListener,
    PlayListener{

    companion object{
        private const val TAG = "VideoControlView"
        private const val PROGRESS_UPDATE_DELAY = 500L
        private const val DEFAULT_CONTROL_UI_HIDE_TIME = 4000
        private const val MAX_BRIGHTNESS = 255
        private const val MAX_PROGRESS = 1000

        // Event constants
        const val EVENT_CONTROL_VIEW = 1001
        const val EVENT_SEEKBAR_START = 1002
        const val EVENT_SEEKBAR_TOUCHING = 1003
        const val EVENT_SEEKBAR_END = 1004
        const val EVENT_CLICK_VIEW = 1005
    }

    private var currentState: Int = IVideoPlayer.STATE_NORMAL
    private var currentMode: Int = IVideoPlayer.MODE_WINDOW_NORMAL

    private var finBinding: FinVideoControlUiBinding =
        FinVideoControlUiBinding.inflate(LayoutInflater.from(context), this, true)

    private var audioManager: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    private var handleTouchEvent: HandleTouchEvent = HandleTouchEvent(this)

    private val uiHandler: Handler = Handler(Looper.getMainLooper())

    //调节前的值 亮度退出全屏应原样
    private var tempPosition = 0
    private var tempBrightness = 0
    private var tempVolume = 0

    private var isShowControlView: Boolean = true
    // Runnable tasks
    private val updateProgressRunnable = Runnable { updateProgressTask() }
    private val dismissControlViewRunnable = Runnable { dismissControlViewTask() }
    private val hideLockBtnRunnable = Runnable { hideLockBtnTask() }

    //声音控制/亮度控制
    private val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    private val minVolume = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
    } else {
        0
    }
    private val indicatorMax = 20
    private val volumeStep = (maxVolume - minVolume) / indicatorMax.toFloat()
    private val brightnessStep = 255F / indicatorMax

    private lateinit var controlViewAction: IControlViewAction
    private var captureBitmap: Bitmap? = null

    init {
        finBinding.videoControllerSeekBar.apply {
            max = MAX_PROGRESS
            setOnSeekBarChangeListener(this@VideoControlView)
        }
        setupViewListeners()

        handleViewPadding(context)
    }

    /**
     * 窗口边衬区（WindowInsets）的适配，主要功能是在全屏模式下为控制栏和操作按钮添加适当的内边距，以避免与系统 UI（如状态栏、导航栏）重叠
     */
    private fun handleViewPadding(context: Context) {
        // 控制栏、操作按钮
        val bottomBarInitPaddingLeft = finBinding.videoControllerBottomBar.paddingLeft
        val bottomBarInitPaddingRight = finBinding.videoControllerBottomBar.paddingRight
        val lockBtnLp = finBinding.videoControllerLockBtn.layoutParams as MarginLayoutParams
        val lockBtnInitMarginLeft = lockBtnLp.leftMargin
        ViewCompat.setOnApplyWindowInsetsListener(finBinding.videoControllerTopBar) { v, insets ->
            var paddingLr = 0
            var paddingTop = 0
            if (currentMode == MODE_WINDOW_FULLSCREEN) {
                paddingLr = max(insets.stableInsetLeft, insets.stableInsetRight)
                //if (host.activity.screenOrientation() == Configuration.ORIENTATION_LANDSCAPE) {
                if (!Util.isScreenOrientationPortrait(context)) {
                    paddingLr = max(Util.dp2px(context, 60f), paddingLr)
                    paddingTop = 0
                } else {
                    paddingTop = insets.stableInsetTop
                }
            }

            // top bar
            v.setPadding(paddingLr, paddingTop, paddingLr, v.paddingBottom)

            // bottom bar
            finBinding.videoControllerBottomBar.setPadding(
                paddingLr + bottomBarInitPaddingLeft,
                finBinding.videoControllerBottomBar.paddingTop,
                paddingLr + bottomBarInitPaddingRight,
                finBinding.videoControllerBottomBar.paddingBottom
            )

            // lock btn
            lockBtnLp.leftMargin = paddingLr + lockBtnInitMarginLeft
            finBinding.videoControllerLockBtn.layoutParams = lockBtnLp

            // capture btn、capture result
            finBinding.videoControllerCaptureView.setPadding(
                finBinding.videoControllerCaptureView.paddingLeft,
                finBinding.videoControllerCaptureView.paddingTop,
                paddingLr,
                finBinding.videoControllerCaptureView.paddingBottom
            )

            insets
        }
    }


    fun bindWith(action: IControlViewAction){
        this.controlViewAction = action
    }

    private fun setupViewListeners() {
        //手势监听
        finBinding.root.setOnTouchListener { _, event ->
            handleTouchEvent.handleEvent(finBinding.root, event)
        }

        //点击空白处，显示或影藏 底部控制ui
        finBinding.root.setOnClickListener{

            Log.i("test", "controlView has clicked....")
            //处理锁图标的显示与隐藏
            if(currentMode === MODE_WINDOW_FULLSCREEN && isLockFullScreen()){
                isShowControlView = !isLockBtnShow()
                showLockBtn()

                return@setOnClickListener
            }

            when (currentState) {
                //STATE_NORMAL, STATE_ERROR -> handlePlayAction()
                STATE_PLAYING, STATE_PAUSE, STATE_AUTO_COMPLETE -> {
                    isShowControlView = !isShowControlView
                    showOrHideControllerView()
                    if(currentMode === MODE_WINDOW_FULLSCREEN) showLockBtn()

                }
            }
        }
        //底部播放按钮
        finBinding.videoControllerBottomPlayBtn.setOnClickListener{
            controlViewAction.handlePlayAction()
        }
        //中间播放按钮
        finBinding.videoControllerCenterPlayBtn.setOnClickListener{
            controlViewAction.handlePlayAction()
        }
        //是否静音
        finBinding.videoControllerMutedBtn.setOnClickListener{
            it.isSelected = !it.isSelected
            controlViewAction.setMute(it.isSelected)
        }
        finBinding.videoControllerFullscreenBtn.setOnClickListener{
            if (currentMode === MODE_WINDOW_FULLSCREEN) {
                controlViewAction.quitWindowFullscreen()
            } else {
                //进入全屏前，先将锁屏图标重置为未锁定状态
                updateLockBtnStatus(false)
                controlViewAction.enterWindowFullscreen()
            }
        }
        finBinding.videoControllerBackBtn.setOnClickListener{
            //退出全屏
            if (currentMode === MODE_WINDOW_FULLSCREEN) {
                controlViewAction.quitWindowFullscreen()
            }
        }
        //屏幕锁
        finBinding.videoControllerLockBtn.setOnClickListener{
            isShowControlView = it.isSelected
            it.isSelected = !it.isSelected
            if(it.isSelected) startHideLockBtnTimer()

            showOrHideControllerView()
        }
        //弹幕
        finBinding.videoControllerDanmuBtn.setOnClickListener{
            it.isSelected = !it.isSelected
            if(it.isSelected) controlViewAction.showDanmu()
            else controlViewAction.hideDanmu()
        }
        //截图
        finBinding.videoControllerCaptureBtn.setOnClickListener{
            captureBitmap = controlViewAction.getCurrentFrame()
            captureBitmap?.let { bitmap ->

                finBinding.videoControllerCaptureResultImg.setImageBitmap(bitmap)
                finBinding.videoControllerCaptureResult.visibility = VISIBLE
                finBinding.videoControllerCaptureResult.postDelayed({
                    finBinding.videoControllerCaptureResult.visibility = GONE
                    finBinding.videoControllerCaptureResultImg.setImageDrawable(null)
                },6000L)
                //checkAndSaveBitmap(bitmap)
                saveBitmapToGallery(bitmap)
            } ?: showMessage("无法获取当前视频帧")

        }
    }

    fun updateUIWithOptions(){
        //controls
        visibility = if(playerOptions.controls) VISIBLE else GONE
        //是否展示弹幕
        finBinding.videoControllerDanmuBtn.visibility = if (playerOptions.danmuBtn) VISIBLE else GONE
        //是否默认显示弹幕
        finBinding.videoControllerDanmuBtn.isSelected = playerOptions.enableDanmu
        //是否静音
        finBinding.videoControllerMutedBtn.isSelected = playerOptions.muted
        //是否显示静音按钮
        finBinding.videoControllerMutedBtn.visibility = if(playerOptions.showMuteBtn) VISIBLE else GONE
        //是否显示全屏按钮
        finBinding.videoControllerFullscreenBtn.visibility = if(playerOptions.showFullscreenBtn) VISIBLE else GONE
        //是否显示底部控制栏播放按钮
        //finBinding.videoControllerBottomPlayBtn.visibility = if(options.showPlayBtn) VISIBLE else GONE
        //是否显示底部进度条
        finBinding.videoControllerSeekBar.visibility = if(playerOptions.showProgress) VISIBLE else GONE
        //是否显示视频中间的播放按钮
        finBinding.videoControllerCenterPlayBtn.visibility = if(playerOptions.showCenterPlayBtn) VISIBLE else GONE
        //是否显示投屏按钮
        finBinding.videoControllerTvCast.visibility = if(playerOptions.showCastingButton) VISIBLE else GONE
        //是否显示锁屏按钮 全屏时才出现
        finBinding.videoControllerLockBtn.visibility = if(playerOptions.showScreenLockButton) VISIBLE else GONE
        //是否显示截屏按钮 全屏时才出现
        finBinding.videoControllerCaptureBtn.visibility = if(playerOptions.showSnapshotButton) VISIBLE else GONE
        //设置title
        finBinding.videoControllerTitle.text = playerOptions.title
    }

    // region UI State Management
    private fun showPlayBtnView(isPlaying: Boolean, isBeforStart: Boolean = false){
        val position = playerOptions.playBtnPosition
        val bottomBtnShow = playerOptions.showPlayBtn
        val centerBtnShow = playerOptions.showCenterPlayBtn
        Log.i(TAG, "showPlayBtnView position: $position, bottomBtnShow: $bottomBtnShow, centerBtnShow: $centerBtnShow, isBeforStart: $isBeforStart")
        when(position){
            PlayBtnPosition.BOTTOM.value ->{
                finBinding.videoControllerBottomPlayBtn.visibility = if (bottomBtnShow) VISIBLE else GONE
                //开始播放前显示，播放后不显示
                finBinding.videoControllerCenterView.visibility = if (centerBtnShow && isBeforStart) VISIBLE else GONE
            }
            PlayBtnPosition.CENTER.value ->{
                finBinding.videoControllerBottomPlayBtn.visibility = GONE
                finBinding.videoControllerCenterView.visibility = if (centerBtnShow) VISIBLE else GONE
            }
        }

        if(finBinding.videoControllerBottomPlayBtn.visibility == VISIBLE){
            finBinding.videoControllerBottomPlayBtn.isSelected = isPlaying
        }
        //如果显示中间播放按钮，则显示中间的时长文本
        if(finBinding.videoControllerCenterView.visibility == VISIBLE){
            finBinding.videoControllerCenterPlayBtn.isSelected = isPlaying

            if(controlViewAction.getPosition()>0){
                finBinding.videoControllerCenterDuration.text = Util.stringForTime(controlViewAction.getPosition())
            }else{
                finBinding.videoControllerCenterDuration.text = Util.stringForTime(controlViewAction.getDuration())
            }
        }

    }

    /**
     * 显示或影藏底部控制view
     */
    private fun showOrHideControllerView(isShow: Boolean = isShowControlView, withHideTask: Boolean = true){
        cancelDismissControlViewTimer()

        if(isShow){
            finBinding.videoControllerBottomBar.visibility = View.VISIBLE

            //全屏显示topView，否则隐藏
            if (currentMode == IVideoPlayer.MODE_WINDOW_NORMAL) finBinding.videoControllerTopBar.visibility = View.INVISIBLE
            if (currentMode == IVideoPlayer.MODE_WINDOW_FULLSCREEN) finBinding.videoControllerTopBar.visibility = View.VISIBLE

            if (withHideTask){
                startDismissControlViewTimer()
            }
        }else{
            finBinding.videoControllerBottomBar.visibility = View.INVISIBLE
            finBinding.videoControllerTopBar.visibility = View.INVISIBLE
        }
    }

    /**
     * 状态和模式变更，通知ui更新
     */
    private fun updateUIWithStateAndMode(status: Int, mode: Int) {
        Log.i("test", "updateUIWithStateAndMode status:$status mode:$mode")
        cancelDismissControlViewTimer()
        cancelProgressTimer()
        //加载视频loading
        onBuffering(false)
        //默认是暂停播放按钮
        showPlayBtnView(false)
        updateFullscreenBtnStatus()
        showLockBtn(mode==MODE_WINDOW_FULLSCREEN)
        finBinding.videoControllerThumb.visibility = GONE
        when (status) {
            STATE_NORMAL, STATE_PREPARING -> {
                resetProgressAndTime()
                onBuffering(true)
            }
            STATE_PLAYING -> {
                startProgressTimer()
                //加载完成开始播放时，显示下控制ui
                this.isShowControlView = true
                showOrHideControllerView()
                showPlayBtnView(true)
            }
            STATE_PAUSE -> {
                val curPosition = controlViewAction.getPosition()
                if(curPosition == playerOptions.initialTime.toInt()*1000){

                    if(playerOptions.controls && playerOptions.poster.isNotEmpty()){
                        //处理封面
                        //finBinding.videoControllerThumb.setImageResource(R.mipmap.cover)
                        Glide.with(this)
                            .load(playerOptions.poster)
                            .into(finBinding.videoControllerThumb);
                        finBinding.videoControllerThumb.visibility = VISIBLE
                    }
                    //处理开始播放时的播放按钮
                    showPlayBtnView(isPlaying = false, true)
                }

            }
            STATE_ERROR -> {

            }
            STATE_AUTO_COMPLETE -> {
                this.isShowControlView = true
                showOrHideControllerView(isShowControlView, false)
            }
        }
        //handlePlayListener.onEvent(EVENT_CONTROL_VIEW, if (isShowControlView) 0 else 1)
    }


    private fun onBuffering(isBuffering: Boolean) {
        finBinding.videoControllerBuffering.visibility = if (isBuffering) View.VISIBLE else View.GONE
    }
    /**
     * 设置进度条和时间
     */
    private fun setProgressAndText(position: Int = controlViewAction.getPosition().coerceAtLeast(0)) {

        var duration = controlViewAction.getDuration().let { if (it <= 0) 1 else it }
        if (playerOptions.duration>0){
            //如果有配置视频时长，则显示配置的时长
            duration = playerOptions.duration.toInt()*1000
        }

        val progress = ((position.toLong() * MAX_PROGRESS) / duration).toInt().coerceIn(0,
            MAX_PROGRESS
        )
        setProgressBar(progress, finBinding.videoControllerSeekBar)

        //读取弹幕
        controlViewAction.printDanmu(position)

        finBinding.videoControllerPositionTv.text = Util.stringForTime(position)
        finBinding.videoControllerDurationTv.text = if (duration > 1) Util.stringForTime(duration) else context.getString(R.string.online)
    }

    private fun setProgressBar(progress: Int, vararg progressBars: ProgressBar?) {
        progressBars.forEach { it?.progress = progress }
    }

    /**
     * 重置进度条和时间
     */
    private fun resetProgressAndTime() {
        setProgressBar(0, finBinding.videoControllerSeekBar)
        finBinding.videoControllerPositionTv.text = Util.stringForTime(0)
        finBinding.videoControllerDurationTv.text = Util.stringForTime(0)
    }

    private fun updateLockBtnStatus(isLock: Boolean){
        finBinding.videoControllerLockBtn.isSelected = isLock
    }

    private fun updateFullscreenBtnStatus(){
        finBinding.videoControllerFullscreenBtn.isSelected = currentMode == MODE_WINDOW_FULLSCREEN
    }
    private fun showLockBtn(isShow: Boolean = isShowControlView){
        finBinding.videoControllerLockBtn.visibility = if (isShow) View.VISIBLE else View.GONE
        cancelHideLockBtnTimer()
        if(isShow && isLockFullScreen()){
            //如果是锁定状态，且显示，则开启一个延时隐藏task
            startHideLockBtnTimer()
        }
        showSnapshotBtn(isShow)
    }

    private fun showSnapshotBtn(isShow: Boolean = isShowControlView){
        finBinding.videoControllerCaptureBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    private fun isLockFullScreen(): Boolean{
        return finBinding.videoControllerLockBtn.isSelected
    }

    private fun isLockBtnShow():Boolean{
        return finBinding.videoControllerLockBtn.visibility == View.VISIBLE
    }
    // endregion

    // region Timer Management
    private fun startProgressTimer() {
        cancelProgressTimer()
        uiHandler.post(updateProgressRunnable)
    }

    private fun cancelProgressTimer() {
        uiHandler.removeCallbacks(updateProgressRunnable)
    }

    private fun updateProgressTask() {
        uiHandler.postDelayed(updateProgressRunnable, PROGRESS_UPDATE_DELAY)
        setProgressAndText()
    }

    private fun startDismissControlViewTimer(delay: Int = DEFAULT_CONTROL_UI_HIDE_TIME) {
        cancelDismissControlViewTimer()
        uiHandler.postDelayed(dismissControlViewRunnable, delay.toLong())
    }

    private fun cancelDismissControlViewTimer() {
        uiHandler.removeCallbacks(dismissControlViewRunnable)
    }

    private fun startHideLockBtnTimer(delay: Int = DEFAULT_CONTROL_UI_HIDE_TIME) {
        cancelHideLockBtnTimer()
        uiHandler.postDelayed(hideLockBtnRunnable, delay.toLong())
    }

    private fun cancelHideLockBtnTimer() {
        uiHandler.removeCallbacks(hideLockBtnRunnable)
    }

    /**
     * 隐藏controllerView
     */
    private fun dismissControlViewTask() {
        isShowControlView = false
        showOrHideControllerView()
        showLockBtn()
        //handlePlayListener.onEvent(FinVideoView.EVENT_CONTROL_VIEW, if (isShowControlView) 0 else 1)
    }

    private fun hideLockBtnTask() {
        showLockBtn(false)
    }
    // endregion

    // region Gesture Handling
    override fun onGestureBegin(type: Int) {
        //锁屏下不能使用手势
        if (isLockFullScreen()) return
        //进度
        if((type == HandleTouchEvent.GestureEvent.TOUCH_FULL_X)
            and controlViewAction.checkReady()){

            if(playerOptions.enableProgressGesture){
                tempPosition = controlViewAction.getPosition()
                //显示控制view
                isShowControlView = true
                showOrHideControllerView(withHideTask = false)
            }
        }

        if(currentMode == MODE_WINDOW_FULLSCREEN){
            //全屏模式
            if(playerOptions.vslideGestureInFullscreen){
                handleBrightAndVoiceAtGestureBegin(type)
            }
        }else{
            //非全屏模式
            if(playerOptions.vslideGesture){
                handleBrightAndVoiceAtGestureBegin(type)
            }
        }
    }

    private fun handleBrightAndVoiceAtGestureBegin(type: Int) {
        //亮度
        if (type == HandleTouchEvent.GestureEvent.TOUCH_LEFT_Y) {
            tempBrightness =
                (Util.scanForActivity(context).window.attributes.screenBrightness * 255).toInt()
            if (tempBrightness < 0) try { //系统亮度 不能activity取
                tempBrightness = Settings.System.getInt(
                    context.contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS
                )
            } catch (e: SettingNotFoundException) {
                e.printStackTrace()
                tempBrightness = 0
            }
            showBrightnessDialog()
        }

        //音量
        if (type == HandleTouchEvent.GestureEvent.TOUCH_RIGHT_Y) {
            showVolumeDialog()
            tempVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        }
    }

    override fun onGestureChange(type: Int, level: Float) {
        //锁屏下不能使用手势
        if (isLockFullScreen()) return

        //进度
        if (playerOptions.enableProgressGesture
            and (type == HandleTouchEvent.GestureEvent.TOUCH_FULL_X)
            and controlViewAction.checkReady()) {

            val duration = controlViewAction.getDuration()
            if (duration <= 1) return
            // 使用改进的delta计算
            //val delta = calculateSmoothSeekDelta(level, duration, tempPosition)
            //拖动开始慢 后面快
            var delta = (level * abs(level.toDouble()) * duration).toInt()
            delta.coerceIn(-tempPosition, (duration - tempPosition).toInt())
            showSeekingIndicator(delta, tempPosition)
        }

        if(currentMode == MODE_WINDOW_FULLSCREEN){
            //全屏模式
            if(playerOptions.vslideGestureInFullscreen){
                handleBrightAndVoiceAtGestureChange(type, level)
            }
        }else{
            //非全屏模式
            if(playerOptions.vslideGesture){
                handleBrightAndVoiceAtGestureChange(type, level)
            }
        }
    }

    private fun handleBrightAndVoiceAtGestureChange(type: Int, level: Float) {
        //亮度
        if (type == HandleTouchEvent.GestureEvent.TOUCH_LEFT_Y) {
            changeBrightnessDialog(level)
        }

        //音量
        if (type == HandleTouchEvent.GestureEvent.TOUCH_RIGHT_Y) {
            volumeChange(level)
        }
    }

    override fun onGestureEnd(type: Int, level: Float) {

        //双击播放/暂停
        if (playerOptions.enablePlayGesture
            and (type == HandleTouchEvent.GestureEvent.TOUCH_DOUBLE_C))
            controlViewAction.handlePlayAction()

        //锁屏下不能使用手势
        if (isLockFullScreen()) return

        //进度
        if (playerOptions.enableProgressGesture
            and (type == HandleTouchEvent.GestureEvent.TOUCH_FULL_X)
            and controlViewAction.checkReady()) {
            val duration = controlViewAction.getDuration()
            if (duration <= 0) return
            hideSeekingIndicator()
            val delta: Int = (level * abs(level.toDouble()) * duration).toInt()
            tempPosition +=delta
            if (tempPosition > duration) tempPosition = duration
            if (tempPosition < 0) tempPosition = 0
            controlViewAction.seekTo(tempPosition)
        }

        if(currentMode == MODE_WINDOW_FULLSCREEN){
            //全屏模式
            if(playerOptions.vslideGestureInFullscreen){
                handleBrightAndVoiceAtGestureEnd(type)
            }
        }else{
            //非全屏模式
            if(playerOptions.vslideGesture){
                handleBrightAndVoiceAtGestureEnd(type)
            }
        }

        if (currentMode === MODE_WINDOW_FULLSCREEN) {
            //Util.hideBottomUIMenu(getContext());
        }
    }

    private fun handleBrightAndVoiceAtGestureEnd(type: Int) {
        //亮度
        if (type == HandleTouchEvent.GestureEvent.TOUCH_LEFT_Y) {
            hideVolumeOrBrightnessDialog()
        }

        //音量
        if (type == HandleTouchEvent.GestureEvent.TOUCH_RIGHT_Y) {
            hideVolumeOrBrightnessDialog()
        }
    }

    private fun showSeekingIndicator(delta: Int, position: Int): Boolean{

        finBinding.videoControllerSeekingIndicator.visibility = VISIBLE
        finBinding.videoControllerSeekingIndicator.text = Util.stringForTime(position + delta)

        //联动seekbar
        setProgressAndText(position + delta)
        return true
    }

    private fun hideSeekingIndicator(){
        startDismissControlViewTimer()
        finBinding.videoControllerSeekingIndicator.visibility = GONE
    }

    private fun showBrightnessDialog(){
        finBinding.videoControllerIndicator.run {
            show(R.drawable.fin_ic_brightness, indicatorMax)
            setProgress(((context as Activity).window.attributes.screenBrightness / brightnessStep).toInt())
        }
    }

    private fun changeBrightnessDialog(percentDelta: Float) {
        val attributes = (context as Activity).window.attributes
        val pendingBrightness = tempBrightness + (percentDelta*255).toInt()
        val brightness = max(min(255, pendingBrightness), 1)

        attributes.screenBrightness = brightness /255.0f
        (context as Activity).window.attributes = attributes
        finBinding.videoControllerIndicator.setProgress((brightness / brightnessStep).toInt())
    }

    private fun showVolumeDialog(){
        finBinding.videoControllerIndicator.run {
            show(R.drawable.fin_ic_volume_indicator, indicatorMax)
            setProgress((audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) / volumeStep).toInt())
        }
    }

    private fun volumeChange(percent: Float) {
        val pendingVolume = tempVolume + (percent * (maxVolume - minVolume)).toInt()
        val volume = max(min(pendingVolume, maxVolume), minVolume)
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0)
        finBinding.videoControllerIndicator.setProgress((volume / volumeStep).toInt())
    }

    private fun hideVolumeOrBrightnessDialog(){
        finBinding.videoControllerIndicator.hide()
    }
    // endregion

    //region PlayList implement
    override fun onStatusAndMode(status: Int, mode: Int) {
        Log.i("test", "onStatusAndMode--status: $status, mode: $mode")
        this.currentMode = mode
        this.currentState = status
        updateUIWithStateAndMode(status, mode)
    }

    override fun onEvent(what: Int, vararg extra: Int?) {

    }

    // endregion

    // region SeekBar Listeners
    fun changeSeekBarProgressFromOperate(time: Int){
        /*// 1. 模拟开始拖动
        onStartTrackingTouch(finBinding.videoControllerSeekBar)
        // 2. 模拟进度变化，并指定 fromUser 为 true 以表示是用户操作
        finBinding.videoControllerSeekBar.progress = position
        // 3. 模拟结束拖动
        onStopTrackingTouch(finBinding.videoControllerSeekBar)*/

        controlViewAction.seekTo(time)
    }
    override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
        //todo
        if (fromUser && controlViewAction.getDuration() > 1) {
            val time = progress * controlViewAction.getDuration() / MAX_PROGRESS
            finBinding.videoControllerPositionTv.text = Util.stringForTime(time)
            //handlePlayListener.onEvent(EVENT_SEEKBAR_TOUCHING, progress,MAX_PROGRESS)
        }
    }

    override fun onStartTrackingTouch(seekBar: SeekBar) {
        cancelProgressTimer()
        cancelDismissControlViewTimer()
        //handlePlayListener.onEvent(EVENT_SEEKBAR_START)
    }

    override fun onStopTrackingTouch(seekBar: SeekBar) {
        if (controlViewAction.getDuration() > 1) {
            val time = seekBar.progress * controlViewAction.getDuration() / MAX_PROGRESS
            controlViewAction.seekTo(time)
        }
        startProgressTimer()
        if (currentState == STATE_PLAYING) startDismissControlViewTimer()
        //handlePlayListener.onEvent(EVENT_SEEKBAR_END)
    }
    // endregion

    //region 截屏处理
    // 修改回调定义，只负责启动权限请求
    //var onPermissionRequest: (() -> Unit)? = null

    // 添加权限结果回调
    //private var onPermissionResult: ((Boolean) -> Unit)? = null

    /*override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        // 设置权限结果回调
        onPermissionResult = { granted ->
            if (granted) {
                saveBitmapToGallery(captureBitmap)
            } else {
                showMessage("需要存储权限才能保存截图")
            }
        }
        (context.getActivity() as IPermissionRequestListener).setPermissionRequestForControllView(this@VideoControlView)
    }*/

    /*override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        (context.getActivity() as IPermissionRequestListener).unSetPermissionRequestForControllView()
        onPermissionResult = null
    }*/

    // 提供给Activity获取回调的方法
    /*fun getPermissionResultCallback(): ((Boolean) -> Unit)? {
        return onPermissionResult
    }*/

    /*private fun checkAndSaveBitmap(bitmap: Bitmap) {
        if (PermissionUtils.hasStoragePermission(context)) {
            // 有权限，直接保存
            saveBitmapToGallery(bitmap)
        } else {
            // 请求权限
            requestStoragePermission()
        }
    }*/

    /*private fun requestStoragePermission() {
        // 请求权限
        (context.getActivity() as? IPermissionRequestListener)?.requestStoragePermission()
            ?: showMessage("权限请求功能未设置")
    }*/

    private fun saveBitmapToGallery(bitmap: Bitmap?) {
        bitmap?.let {
            BitmapSaveUtils.saveBitmapToGallery(
                context = context,
                bitmap = it,
                onSuccess = { message ->
                    showMessage(message)
                },
                onError = { error ->
                    showMessage(error)
                }
            )
        }
    }
    private fun showMessage(message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }
    // Context扩展，用于获取Activity
    /*private fun Context.getActivity(): android.app.Activity? {
        var context = this
        while (context is android.content.ContextWrapper) {
            if (context is android.app.Activity) {
                return context
            }
            context = context.baseContext
        }
        return null
    }*/
    //endregion


    interface IControlViewAction{
        fun handlePlayAction()
        fun setMute(boolean: Boolean)
        fun quitWindowFullscreen()
        fun enterWindowFullscreen()
        fun getPosition():Int
        fun getDuration():Int
        fun checkReady():Boolean
        fun seekTo(duration: Int)
        fun showDanmu()
        fun hideDanmu()
        fun printDanmu(position: Int)
        fun getCurrentFrame(): Bitmap?
    }

    /*interface IPermissionRequestListener{
        fun setPermissionRequestForControllView(videoControlView: VideoControlView)
        fun unSetPermissionRequestForControllView()
        fun requestStoragePermission()
    }*/
}